/*
   Copyright 2011 
   
   DIFED

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package difed.restaurante;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import difed.restaurante.db.ProveedorBD;
import difed.restaurante.db.ProveedorBDImpl;
import difed.restaurante.entidades.RestCheck;
import difed.restaurante.entidades.Restaurante;

public class ExpActivity extends Activity {

    private RestCheck resCheck;
    List<RestCheck> lrestaurantes;

    Set<String> seleccionados;

    View restaurantView = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (resCheck == null) {
            resCheck = new RestCheck();
        }

        seleccionados = new HashSet<String>();

        buildView();
    }

    private void buildView() {

        setContentView(R.layout.expimp);

        ViewGroup restaurantList = (ViewGroup) findViewById(R.id.expimp_list);

        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

        TextView textView;

        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/fuente.ttf");
        textView = (TextView) findViewById(R.id.expimp_titulo);
        textView.setText(R.string.exp);
        textView.setTypeface(tf);
        
        

        ProveedorBD proveedor = ProveedorBDImpl.getProveedor(this);
        lrestaurantes = new ArrayList<RestCheck>();

        lrestaurantes = proveedor.lRestaurantesCheck();

        for (RestCheck rest : lrestaurantes) {
            restaurantView = inflater.inflate(R.layout.expimp_block, null);

            Typeface tf2 = Typeface.createFromAsset(getAssets(),
                    "fonts/kberry.ttf");

            textView = (TextView) restaurantView
                    .findViewById(R.id.expimp_label);
            textView.setTypeface(tf2);
            textView.setText(rest.getNombre());

            final CheckBox cb = (CheckBox) restaurantView
                    .findViewById(R.id.expimp_check);
            cb.setTag(rest.getNombre());
            cb
                    .setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
                        public void onCheckedChanged(CompoundButton buttonView,
                                boolean isChecked) {
                            if (isChecked) {
                                seleccionados.add((String) cb.getTag());
                            } else {
                                seleccionados.remove((String) cb.getTag());
                            }
                        }
                    });

            restaurantList.addView(restaurantView);

        }

    }

    @SuppressWarnings("unchecked")
    public void botonPulsado(View v) {
        
              
        ProveedorBD proveedor = ProveedorBDImpl.getProveedor(this);
        if (v.getId() == R.id.expimp_aceptar) {

            // Si se ha checkeado alguno entonces
            if (!seleccionados.isEmpty()) {
                // obtenemos de cada chequeado sus datos u los vamos insertando
                // en una lista
                List<Restaurante> lRestSeleccionados = new ArrayList<Restaurante>();
                Iterator it = seleccionados.iterator();

                while (it.hasNext()) {
                    String value = (String) it.next();
                    Restaurante restaurante = new Restaurante();
                    restaurante = proveedor.getRestaurante(value);

                    lRestSeleccionados.add(restaurante);
                }

                // Vamos leyendo la lista e insertandola en el fichero

                try {
                    FileWriter fstream = new FileWriter(
                            "/sdcard/restaurant/enviar.txt");
                    BufferedWriter out = new BufferedWriter(fstream);
                    for (Restaurante rest : lRestSeleccionados) {
                        if (rest.getNombre()!=null) {
                            out.write("NO:" + rest.getNombre().trim() + "\n");
                        }else{
                            out.write("NO:\n");
                        }
                        if (rest.getDireccion()!=null) {
                            String direccion=rest.getDireccion();
                            direccion=direccion.replace("\n", "&");
                            out.write("DI:" + direccion + "\n");
                        }else{
                            out.write("DI:\n");                            
                        }
                        if (rest.getTelefono1()!=null) {
                            out.write("T1:" + rest.getTelefono1() + "\n");
                        }else{
                            out.write("T1:\n");                            
                        }
                        if (rest.getTelefono2()!=null) {
                            out.write("T2:" + rest.getTelefono2() + "\n");
                        }else{
                            out.write("T2:\n");                            
                        }
                        if (rest.getId_poblacion()!=null) {
                            out.write("PO:" + rest.getId_poblacion() + "\n");
                        }else{
                            out.write("PO:\n");                            
                        }
                        if (rest.getId_provincia()!=null) {
                            out.write("PR:" + rest.getId_provincia() + "\n");
                        }else{
                            out.write("PR:\n");                            
                        }
                        if (rest.getId_tipo()!=null) {
                            out.write("TI:" + rest.getId_tipo() + "\n");
                        }else{
                            out.write("TI:\n");                            
                        }
                        if (rest.getSugerencias()!=null) {
                            out.write("SU:" + rest.getSugerencias() + "\n");
                        }else{
                            out.write("SU:\n");                            
                        }
                        if (rest.getNotas()!=null) {
                            String notas=rest.getNotas();
                            notas=notas.replace("\n", "&");
                            out.write("NT:" + notas + "\n");
                        }else{
                            out.write("NT:\n");                            
                        }
                        
                    }

                    out.close();
                    
                    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                    alertDialog.setTitle("Enviar");
                    String message="Se ha creado un fichero en sdcard->restaurant llamado enviar.txt\ncon los restaurantes elegidos.";
                    alertDialog.setMessage(message);
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int which) {
                           finish();
                       }
                    });
                    // Set the Icon for the Dialog
                    alertDialog.setIcon(R.drawable.icon);
                    alertDialog.show();
                    
                    
                    //Toast.makeText(getApplicationContext(), "Exportados con exito", Toast.LENGTH_SHORT).show();
                   

                } catch (Exception e) {// Catch exception if any
                    System.err.println("Error: " + e.getMessage());
                }

               
            }

        }

    }
}
